import { defineStore } from 'pinia'
import { useDark, useToggle } from '@vueuse/core'

export const useAppStore = defineStore('ipp', {
  state: () => ({
    isDark: false,
    version: 'v1.0.0.2025042901'
  }),
  actions: {
    toggleDark(e: MouseEvent) {
      const toggleDark = useToggle(useDark())

      if (!document.startViewTransition) {
        toggleDark()
        this.isDark = !this.isDark
        return
      }

      const transition = document.startViewTransition(() => {
        toggleDark() // 实际切换主题
      })

      transition.ready.then(() => {
        const x = e.clientX
        const y = e.clientY
        // 从点击点到窗口最远边缘的距离，这个距离即为圆的半径，用于确定一个圆形裁剪路径 (clip path) 的最大尺寸，以便覆盖整个视窗。
        // 勾股定理：a² + b² = c²
        const a = Math.max(x, window.innerWidth - x)
        const b = Math.max(y, window.innerHeight - y)
        const radius = Math.sqrt((a ** 2) + (b ** 2))

        const clipPath = [`circle(0 at ${x}px ${y}px)`, `circle(${radius}px at ${x}px ${y}px)`]
        // 实现过渡的过程 circle
        document.documentElement.animate(
          {
            clipPath: this.isDark ? clipPath.reverse() : clipPath
          },
          {
            duration: 500,
            easing: 'ease-in',
            pseudoElement: this.isDark ? '::view-transition-old(root)' : '::view-transition-new(root)'
          }
        )
      })

      this.isDark = !this.isDark
    }
  }
})
